// pages/goodsmanage/goodsmanage.js
var area = require('../../data/area')
var g = 0,
  l = 0
var app = getApp()
var api = require("../../config/api.js")
var comm = require("../../utils/comm.js")
var sliderWidth = 96; // 需要设置slider的宽度，用于计算中间位置
Page({

  /**
   * 页面的初始数据
   */
  data: {

    inputShowed: false,
    inputVal: "",

    startNum: 1, //页数

    total: '0',

    search: false, //判断模糊查询方法

    tabs: ["商品列表", "新增商品", ],
    activeIndex: 0,
    sliderOffset: 0,
    sliderLeft: 0,

    toast1Hidden: true,
    modalHidden: true,
    modalHidden2: true,
    notice_str: '',

    files: [],
    files1: [],

    myAgentList: {
      hasMore: true,
      list: [],
      listSize: 0
    },

    curisOnSale: '',

    showMessage: false,
    messageContent: '',
    showDistpicker: false,

    categoryall: [], //所有分类
    categoryscond:[],//二级分类
    Categoryl1: [],
    Categorycodel1: [],
    CategoryIndexl1: '',
    Categoryl2: [],
    Categorycodel2: [],
    CategoryIndexl2: '',

    onsale: 1,
    isnew: 1,

    primaryPicUrl: '', //主图
    listPicUrl: '', //列表图

  },


  //商品上下架
  ononsale: function() {
    if (this.data.onsale == 0) {
      this.setData({
        onsale: 1
      })
    } else {
      this.setData({
        onsale: 0
      })
    }
  },




  //是否为新商品
  onnew: function() {
    if (this.data.isnew == 0) {
      this.setData({
        isnew: 1
      })
    } else {
      this.setData({
        isnew: 0
      })
    }
  },



  //选择商品列表图
  chooseImage: function(e) {
    var that = this;
    var len = that.data.files.length;
    if (len < 8) {
      comm.getUploadImg().then(function(link) {
        if (link !== undefined) {
          that.setData({
            files: that.data.files.concat(link)
          });
        } else(
          wx.showToast({
            title: '图片上传失败',
            icon: "none"
          })
        )
      })
    } else {
      wx.showToast({
        title: '图片数量已达到最大限制',
        icon: "none"
      })
    }


  },

  //选择商品主图
  chooseImage1: function(e) {
    var that = this;
    var len = that.data.files1.length;
    if (len < 1) {
      comm.getUploadImg().then(function(link) {
        if (link !== undefined) {
          that.setData({
            files1: that.data.files1.concat(link)
          });
        } else(
          wx.showToast({
            title: '图片上传失败',
            icon: "none"
          })
        )
      })
    } else {
      wx.showToast({
        title: '图片数量已达到最大限制',
        icon: "none"
      })
    }

  },

  //预览商品列表图片
  previewImage: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },

  //预览商品主图片
  previewImage1: function(e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files1 // 需要预览的图片http链接列表
    })
  },

  //删除列表图片
  deleteImage: function(e) {
    var that = this;
    var files = that.data.files;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      confirmColor: "#43CBC9",
      success: function(res) {
        if (res.confirm) {
          console.log('点击确定了');
          files.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files
        });
      }
    })
  },

  //删除主图片
  deleteImage1: function(e) {
    var that = this;
    var files1 = that.data.files1;
    var index = e.currentTarget.dataset.index; //获取当前长按图片下标
    wx.showModal({
      title: '提示',
      content: '确定要删除此图片吗？',
      confirmColor: "#43CBC9",
      success: function(res) {
        if (res.confirm) {
          console.log('点击确定了');
          files1.splice(index, 1);
        } else if (res.cancel) {
          console.log('点击取消了');
          return false;
        }
        that.setData({
          files1
        });
      }
    })
  },

  // 搜索框状态
  showInput: function() {
    this.setData({
      inputShowed: true
    });
  },
  hideInput: function() {
    this.setData({
      inputVal: "",
      inputShowed: false,
      search: false
    });
    this.onLoad();

  },
  clearInput: function() {
    this.setData({
      inputVal: ""
    });
  },
  inputTyping: function(e) {
    this.setData({
      inputVal: e.detail.value
    });
  },


  //搜索
  searInput: function(e) {
    var _that = this
    console.log(_that.data.inputVal)
    wx.showLoading({
      title: '搜索中',
    })
    if (_that.data.inputVal.length != '') {
      wx.request({
        url: api.GoodsPagList + '?current=1&size=10',
        data: {
          goodsName: _that.data.inputVal,
          current: "1", //请求第一页
          size: "10"
        },
        method: 'POST',
        header: {
          'Accept': 'application/json',
          'ACCESS-TOKEN': wx.getStorageSync('token')
        },
        success: function(res) {
          console.log(res.data)
          wx.hideLoading();
          if (res.data.code == '1') {
            var listSize = res.data.obj.records.length;
            console.log('listSize=' + listSize);
            var newData = _that.data.myAgentList.list;
            newData = res.data.obj.records;
            var total1 = res.data.obj.total;
            var newList = {};
            //当长度小于10表示没有下页数据了
            if (listSize < 10) {
              newList.hasMore = false;
            } else {
              newList.hasMore = true;
            }
            newList.list = newData;
            console.log('newData=' + newData);
            newList.listSize = listSize;
            _that.setData({
              myAgentList: newList
            });
            console.log('myAgentList=' + _that.data.myAgentList);
            _that.setData({
              startNum: 2,
              total: total1,
              search: true
            });

            console.log("newList.list=" + newList.list)

            if (newList.list.length == 0) {
              wx.showModal({
                title: '提示',
                content: "抱歉！你搜索的商品不存在！",
                confirmColor: "#43CBC9",
                showCancel: false,
                success: function(res) {
                  if (res.confirm) {
                    console.log('用户点击确定')
                    _that.hideInput()
                  }
                }
              });
            }



          } else {
            // util.msg("错误", res.data.msg)
            console.log("网络不通，数据不成功")
          }
        },
        fail: function(res) {
          wx.hideLoading();
          console.log(res.data)
          // util.msg("错误", "通讯失败")
        }
      })

    } else {
      wx.showToast({
        title: "输入内容不能为空",
        icon: 'none',
        duration: 2000
      });
    }

  },

  //上拉刷新列表数据
  hotActivityLoadMore: function(e) {
    var _that = this;
    //判断是否还有下一页
    if (_that.data.myAgentList.hasMore == true) {
      wx.showLoading({
        title: '加载中',
      })
      var pageNum = _that.data.startNum
      var _url = api.GoodsPagList + '?current=' + pageNum + '&size=5';
      wx.request({
        url: _url,
        data: {
          userType: "4",
          current: pageNum, //第N页
          size: "5"
        },
        method: 'POST',
        header: {
          'Accept': 'application/json',
          'ACCESS-TOKEN': wx.getStorageSync('token')
        },
        success: function(res) {
          console.log(res.data)
          if (res.data.code == "1") {
            console.log("网络通，数据成功")
            wx.hideLoading();
            var listSize = res.data.obj.records.length;
            var newData = _that.data.myAgentList.list;
            //concat是在原有基础上进行增加
            newData = newData.concat(res.data.obj.records);
            var newList = {};
            //当长度等于于0表示当前没有数据，停止
            if (listSize == 0) {
              newList.hasMore = false;
              wx.showToast({
                title: "已加载全部列表",
                icon: 'none',
                duration: 2000
              });
              return;
              //当长度小于10表示没有下页数据了
            } else if (listSize < 5) {
              wx.showToast({
                title: "已加载全部列表",
                icon: 'none',
                duration: 2000
              });
              newList.hasMore = false;
            } else {
              newList.hasMore = true;
            }
            newList.list = newData;
            newList.listSize = listSize;
            _that.setData({
              myAgentList: newList
            });

            _that.setData({
              startNum: pageNum + 1 //页数加1
            })
          } else {
            // util.msg("错误", res.data.msg)
            console.log("网络不通，数据不成功")
          }

        },
        fail: function(res) {
          console.log(res.data)
          // util.msg("错误", "通讯失败")
          console.log("失败")
        }
      })
    } else {
      wx.showToast({
        title: "已加载全部列表",
        icon: 'none',
        duration: 2000
      });
    }
  },

  //提交新增商品
  formSubmit: function(e) {
    var that = this;
    wx.showModal({
      title: '提示',
      content: '是否确认提交',
      confirmColor: "#43CBC9",
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })

        if (res.confirm) {
          console.log('for发生了submit事件，携带数据为：', e.detail.value);

          var files = that.data.files
          var url = files[0]
          for (var i = 1; i < files.length; i++) {
            url = url + ';' + files[i]
          }
          var primaryPicUrl = that.data.files1[0]
          var listPicUrl = url
          var categoryId = that.data.Categorycodel2[that.data.CategoryIndexl2]

          if (e.detail.value.goodsName.length == 0) {
            wx.showToast({
              title: "请填写商品名称!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (categoryId == undefined) {
            wx.showToast({
              title: "请选择商品类别!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.goodsUnit.length == 0) {
            wx.showToast({
              title: "请填写商品单位!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.goodsNumber.length == 0) {
            wx.showToast({
              title: "请填写库存数量!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.retailPrice.length == 0) {
            wx.showToast({
              title: "请填写零售价格!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.marketPrice.length == 0) {
            wx.showToast({
              title: "请填写市场价格!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.keywords.length == 0) {
            wx.showToast({
              title: "请填写商品关键字!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.goodsBrief.length == 0) {
            wx.showToast({
              title: "请填写简明介绍!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.promotionDesc.length == 0) {
            wx.showToast({
              title: "请填写推广描述!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (e.detail.value.goodsDesc.length == 0) {
            wx.showToast({
              title: "请填写商品详细描述!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (that.data.files1.length == 0) {
            wx.showToast({
              title: "请上传商品主图!",
              icon: 'none',
              duration: 2000
            });
            return false;
          } else if (that.data.files.length == 0) {
            wx.showToast({
              title: "请上传商品列表图!",
              icon: 'none',
              duration: 2000
            });
            return false;
          }

          wx.request({
            url: api.GoodsSave,
            data: {
              goodsName: e.detail.value.goodsName,
              categoryId: categoryId,
              goodsUnit: e.detail.value.goodsUnit,
              goodsNumber: e.detail.value.goodsNumber,
              retailPrice: e.detail.value.retailPrice,
              marketPrice: e.detail.value.marketPrice,
              keywords: e.detail.value.keywords,
              isOnSale: that.data.onsale,
              isNew: that.data.isnew,
              goodsBrief: e.detail.value.goodsBrief,
              promotionDesc: e.detail.value.promotionDesc,
              goodsDesc: e.detail.value.goodsDesc,
              primaryPicUrl: primaryPicUrl, //主图
              listPicUrl: listPicUrl //列表图
            },
            method: 'POST',
            header: {
              'Accept': 'application/json',
              'ACCESS-TOKEN': wx.getStorageSync('token')
            },
            success: function(res) {
              wx.hideLoading();
              if (res.data.success) {
                wx.showModal({
                  title: '提示',
                  content: "成功添加商品",
                  confirmColor: "#43CBC9",
                  showCancel: false,
                  success: function(res) {
                    if (res.confirm) {
                      console.log('用户点击确定')
                      that.clearData()
                      that.setData({
                        activeIndex: 0
                      })
                      that.onLoad()
                    }
                  }
                });
                wx.hideLoading();
              } else {
                console.log("网络通，数据不成功")
              }
            },
            fail: function() {
              wx.hideLoading();
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
                duration: 2000
              });
            },
          })

        } else if (res.cancel) {
          console.log('用户点击取消')
          wx.hideLoading();
        }
      }
    })
  },

  formrs: function() {
    this.clearData()
    wx.showToast({
      title: '清空成功！',
      icon: 'none'
    })
  },

  //清空商品填写数据
  clearData: function() {
    this.setData({
      modalHidden2: false,
      showDistpicker: false,
      goodsName: '',
      CategoryIndexl1: '',
      goodsUnit: '',
      goodsNumber: '',
      retailPrice: '',
      marketPrice: '',
      keywords: '',
      onsale: 1,
      isnew: 1,
      goodsBrief: '',
      promotionDesc: '',
      goodsDesc: '',
      files1: [], //主图
      files: [] //列表图
    });
  },

  //修改商品状态为上架
  sell: function(e) {
    var that = this;
    console.log("e.target.name=" + e.target.name)

    var ID = e.target.id;
    wx.request({
      url: api.GoodsInfoById + ID,
      data: {},
      method: 'GET',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },
      success: (res) => {
        wx.showLoading({
          title: '加载中',
        })
        if (res.data.success) {
          that.setData({
            curisOnSale: res.data.obj.isOnSale
          });
          wx.hideLoading();
          console.log("that.data.curisOnSale" + that.data.curisOnSale)

          if (that.data.curisOnSale == 0) {
            wx.showModal({
              title: '提示',
              content: '是否确认上架该商品？',
              confirmColor: "#43CBC9",
              success: (res) => {
                wx.showLoading({
                  title: '加载中',
                })
                if (res.confirm) {
                  console.log('用户点击确定')

                  wx.request({
                    url: api.GoodsInfoUpd,
                    data: {
                      id: e.target.id,
                      isOnSale: 1,
                    },
                    method: 'POST',
                    header: {
                      'Accept': 'application/json',
                      'ACCESS-TOKEN': wx.getStorageSync('token')
                    },
                    success: function(res) {
                      console.log(res.data)
                      wx.hideLoading();
                      if (res.data.code == '1') {
                        wx.showModal({
                          title: '提示',
                          content: "商品已成功上架!",
                          confirmColor: "#43CBC9",
                          showCancel: false,
                          success: function(res) {
                            if (res.confirm) {
                              console.log('用户点击确定')
                              that.onLoad()
                            }
                          }
                        });
                        wx.hideLoading();
                      } else {
                        console.log("网络通，数据不成功")
                      }
                    },
                    fail: function() {
                      wx.hideLoading();
                      wx.showToast({
                        title: res.data.msg,
                        icon: 'none',
                        duration: 2000
                      });
                    },
                  })

                } else if (res.cancel) {
                  console.log('用户点击取消')
                  wx.hideLoading();
                }
              }
            })
          } else {
            wx.showToast({
              title: "商品已上架!",
              icon: 'none',
              duration: 3000
            });
          }
        }
      }
    })
  },

  //管理商品信息页面跳转
  maginfo: function(e) {
    wx.navigateTo({
      url: '/pages/goodsmanage/goodsinfo?Id=' + e.currentTarget.id,
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    var that = this;
    that.setCatego();
    wx.setStorageSync('getimgUrl', '')
    wx.getSystemInfo({
      success: function(res) {
        that.setData({
          sliderLeft: (res.windowWidth / that.data.tabs.length - sliderWidth) / 2,
          sliderOffset: res.windowWidth / that.data.tabs.length * that.data.activeIndex
        });
      }
    });

    var _that = this
    var _url = api.GoodsPagList + '?current=1&size=5';
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: _url,
      data: {
        current: "1", //请求第一页
        size: "5"
      },
      method: 'POST',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },
      success: function(res) {
        console.log(res.data)
        wx.hideLoading();
        if (res.data.code == '1') {
          var listSize = res.data.obj.records.length;
          console.log('listSize=' + listSize);
          var newData = _that.data.myAgentList.list;
          newData = res.data.obj.records;
          var total1 = res.data.obj.total;
          var newList = {};
          //当长度小于10表示没有下页数据了
          if (listSize < 5) {
            newList.hasMore = false;
          } else {
            newList.hasMore = true;
          }
          newList.list = newData;
          console.log('newData=' + newData);
          newList.listSize = listSize;
          _that.setData({
            myAgentList: newList,
            total: total1
          });

          console.log('myAgentList=' + _that.data.myAgentList);

          _that.setData({
            startNum: 2
          })
        } else {
          // util.msg("错误", res.data.msg)
          console.log("网络通，数据不成功")
        }
      },
      fail: function(res) {
        wx.hideLoading();
        console.log(res.data)
        // util.msg("错误", "通讯失败")
      }
    })


  },

  tabClick: function(e) {
    this.setData({
      sliderOffset: e.currentTarget.offsetLeft,
      activeIndex: e.currentTarget.id
    });
  },



  //弹出确认框  
  modalTap: function(e) {
    this.setData({
      modalHidden: true
    })
  },
  confirm_one: function(e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '提交成功'
    });
  },
  cancel_one: function(e) {
    console.log(e);
    this.setData({
      modalHidden: true,
      toast1Hidden: false,
      notice_str: '取消成功'
    });
  },
  //弹出提示框  
  modalTap2: function(e) {
    this.setData({
      modalHidden2: false
    })
  },
  modalChange2: function(e) {
    this.setData({
      modalHidden2: true
    })
  },
  toast1Change: function(e) {
    this.setData({
      toast1Hidden: true
    });
  },



  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    this.onLoad();

  },


  bindPickerChange: function(e) {
    console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      index: e.detail.value
    })
  },

  //获取一级分类信息
  getCatel1: function() {
    var that = this
    wx.request({
      url: api.GoodsCateGetOne ,
      data: {},
      method: 'GET',
      header: {
        'Accept': 'application/json',
        'ACCESS-TOKEN': wx.getStorageSync('token')
      },
      success: function(res) {
        console.log(res.data)
        wx.hideLoading();
        if (res.data.code == '1') {
          var relsize = res.data.obj.categoryList.length;
          var categoryList = res.data.obj.categoryList;
          var Catl = []
          var Catco = []
          for (var i = 0; i < relsize; i++) {
            Catl = Catl.concat(categoryList[i].categoryName)
            Catco = Catco.concat(categoryList[i].id)
          }
          that.setData({
            Categoryl1: Catl,
            Categorycodel1: Catco
          })
        } else {
          console.log("网络通，数据不成功")
        }
      },
      fail: function(res) {
        wx.hideLoading();
        console.log(res.data)
      }
    })
  },

  //获取二级分类
  getCatel2: function(Id) {
    var that = this
    if (Id) {
      wx.request({
        url: api.GoodsCateGetById + Id,
        data: {},
        method: 'GET',
        header: {
          'Accept': 'application/json',
          'ACCESS-TOKEN': wx.getStorageSync('token')
        },
        success: function(res) {
          console.log(res.data)
          wx.hideLoading();
          if (res.data.code == '1') {
            var relsize = res.data.obj.currentSubCategory.length;
            var categoryList = res.data.obj.currentSubCategory;
            var Catl = [];
            var Catco = [];
            for (var i = 0; i < relsize; i++) {
              Catl = Catl.concat(categoryList[i].categoryName)
              Catco = Catco.concat(categoryList[i].id)
            }
            that.setData({
              Categoryl2: Catl,
              Categorycodel2: Catco
            })
          } else {
            console.log("网络通，数据不成功")
          }
        },
        fail: function(res) {
          wx.hideLoading();
          console.log(res.data)
        }
      })
    }
  },

  //获取商品分类的对象集合
  getAllGoodsCate: function (index) {
    var that = this
    comm.request(api.GoodsAllCate, {}, "GET").then(function(res) {
      if (res.success) {
        var catelist = res.obj
        that.setData({
          categoryall: catelist,
        })
        that.getCgetCateListfrs(index)
      }
    }).catch(function(res) {
      console.log("获取商品分类失败！")
    })
  },

  // 从所有集合中取出一分类
  getCgetCateListfrs: function (index){
    var that = this
    var catelist = that.data.categoryall
    var relsize = that.data.categoryall.length
    var categoryscond = []
    var Catl = []
    var Catco = []
    for (var i = 0; i < relsize; i++) {
      Catl = Catl.concat(catelist[i].categoryName)
      Catco = Catco.concat(catelist[i].id)
    }
    categoryscond = categoryscond.concat(catelist[index].subGoodsCategoryList)
    that.setData({
      Categoryl1: Catl,
      Categorycodel1: Catco,
      categoryscond: categoryscond
    })

    that.getCateListIndex()
  },

  //根据一级参数index选择二级分类的集合
  getCateListIndex: function() {
    var that = this
    var categoryall = that.data.categoryscond
    var relsize = that.data.categoryscond.length
    var Catl = [];
    var Catco = [];
    for (var i = 0; i < relsize; i++) {
      Catl = Catl.concat(categoryall[i].categoryName)
      Catco = Catco.concat(categoryall[i].id)
    }
    that.setData({
      Categoryl2: Catl,
      Categorycodel2: Catco
    })
  },


  setCatego: function(g, l) {
    var that = this
    var g = g || 0
    var l = l || 0
    // //设置一级分类
    // that.getCatel1()
    // // 设置二级分类
    // that.getCatel2(this.data.Categorycodel1[g])
    that.getAllGoodsCate(g)
  },

  changeCate: function(e) {
    g = e.detail.value[0]
    l = e.detail.value[1]
    this.setCatego(g, l)
  },

  distpickerSure: function() {
    this.setData({
      CategoryIndexl1: g,
      CategoryIndexl2: l,
    })
    this.distpickerCancel()
  },

  showDistpicker: function() {
    this.setData({
      showDistpicker: true
    })
  },
  distpickerCancel: function() {
    this.setData({
      showDistpicker: false
    })
  },

  showMessage: function(text) {
    var that = this
    that.setData({
      showMessage: true,
      messageContent: text
    })
    setTimeout(function() {
      that.setData({
        showMessage: false,
        messageContent: ''
      })
    }, 3000)
  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})